package com.yxe.utils;

import cn.hutool.jwt.Claims;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Calendar;
import java.util.Map;

@Component
@Slf4j
public class JwtUtil {

    @Value("${jwt.secret}")
    private String signature;

    @Value("${jwt.expiration}")
    private Integer expiration;

    //创建Jwt
    public String createJwt(Map<String,String> map){
        //时间对象
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE,expiration);//默认一分钟过期
        //Date date = new Date(System.currentTimeMillis() + expiration * 1000);

        //获取Builder对象，目的将集合中的数据，都存储到Jwt的载荷中
        JWTCreator.Builder builder = JWT.create();
        //遍历并赋值载荷信息
        map.forEach( (k,v) -> { builder.withClaim(k,v);});
        //获取Jwt【写一起】
        //String token = builder.withExpiresAt(calendar.getTime()).sign(Algorithm.HMAC256(signature));

        //设置token过期时间
        builder.withExpiresAt(calendar.getTime());
        //生成token
        String token = builder.sign(Algorithm.HMAC256(signature));

        //返回
        return token;
    }

    //验证
    public DecodedJWT verifyJwt(String token){
        return JWT.require(Algorithm.HMAC256(signature)).build().verify(token);
    }

    /**
     * 从token中获取JWT中的负载
     */
    public Map<String, Claim> getClaimsFromToken(String token) {
        Map<String, Claim> claims = null;
        try {
         claims = JWT.require(Algorithm.HMAC256(signature))
                .build()
                .verify(token)
                .getClaims();
        } catch (Exception e) {
            log.info("JWT格式验证失败:{}", token);
        }
        return claims;
    }


}